import sys
import os
import traceback
import ak_stock_fund as ak
import ak_em_hsgt as ake
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import get_stock_data_path as sp
from matplotlib.font_manager import FontProperties

from datetime import datetime

def get_disp_value(v : float)->str:
   if(v >= 100000000.0 or v <= -100000000.0):
     return "%.2f"%float(v/100000000) + "亿"
   elif(v>= 10000.0 or v<= -10000.0):
     return "%.1f"%float(v/10000) + "万"
   else:
     return str(v)


pd.set_option('display.unicode.ambiguous_as_wide', True)
pd.set_option('display.unicode.east_asian_width', True)
pd.set_option('display.max_rows', None)


stock_path = sp.get_stock_data_path()
png_path = sp.get_stock_png_path()
tdx_export_path = sp.get_tdx_export_path()

now = datetime.now()
datestr = datetime.strftime(now,'%Y-%m-%d')
datestr2 = datetime.strftime(now,'%Y%m%d')

tdx_xls = tdx_export_path + sp.get_separator() + "沪深Ａ股" + datestr2 +".txt"
"""
with open(tdx_xls,"a+b") as file:
   file.seek(-17,2)
   es = file.read(8)
   a = bytes.decode(es,encoding="gbk");
   if(a == "数据来源"):
      file.seek(-17,2)
      file.truncate(file.tell())
   file.close()
"""
"""
#本来想从tdx导出的行情txt中得到涨跌家数等，但是由于连续涨停加数没法从一天的行情数据中或取，除非保留之前的涨跌停数据，再读入分析
#所以暂且作罢，还是从sundst.exe里生成
stock_df = pd.read_csv(tdx_xls,sep="\t",encoding="gbk" ,dtype={"代码":str})
del stock_df["Unnamed: 9"]
#tdx_csv= tdx_export_path + sp.get_separator() + "沪深Ａ股" + datestr2 +".csv"
#stock_df.to_csv(tdx_csv,index = False)
cyb_codes=[]
with open(stock_path + sp.get_separator() + "创业板.EBK", "rt") as f:
    for line in f.readlines():
        line = line.strip('\n')  #去掉列表中每一个元素的换行符
        if(len(line) <6):
          continue
        sc = line[1:]
        cyb_codes.append(sc)

cyb_df = stock_df.loc[stock_df['代码'].isin(cyb_codes)]
print(cyb_df.shape[0])
v= cyb_df.values

nr = 0
nd = 0
nr10 = 0
nd10 = 0
rtolimit = 0
dtolimit = 0
rtolimit2 = 0
dtolimit2 = 0
rtolimit3 = 0
dtolimit3 = 0
rtolimit4 = 0
rtolimit0 = 0

drlimit = 1.2
drhalf_limit = 1.1
ddlimit = 0.8
ddhalf_limit = 0.9

for i in range(cyb_df.shape[0]):
   for j in range(cyb_df.shape[1]):
      if(type(v[i][j])==type("1")):
         if(v[i][j].find("--")>=0):
            v[i][j]="0"

for i in range(cyb_df.shape[0]):
    sc = v[i][0]
    lc = int(float(v[i][8])*100)
    tc = int(float(v[i][3])*100)
    th = int(float(v[i][6])*100)
    tl = int(float(v[i][7])*100)
    if(tc > lc):
       rlimit = int((float(lc) * drlimit + 0.5))
       if(th == tc and rlimit == tc):
          nr10 = nr10 + 1
       nr = nr + 1
    elif(tc < lc):
       dlimit = int((float(lc) * ddlimit + 0.5))
       if(tl == tc and dlimit == tc):
          nd10 = nd10 + 1
       nd = nd + 1

print(nr)
print(nd)
"""

ta_csv = stock_path + sp.get_separator() + "market_emotion.csv"
ta_csv_zx = stock_path + sp.get_separator() + "market_emotion_zx.csv"
ta_csv_cy = stock_path + sp.get_separator() + "market_emotion_cy.csv"
fundflow_png = png_path + sp.get_separator() + datestr +"市场情绪.png"

csvs = [ta_csv,ta_csv_zx,ta_csv_cy]
titles = ['A股主板市场情绪监控表','中小板市场情绪监控表','创业板市场情绪监控表']

colors = plt.cm.Reds(np.linspace(0.8, 0.4, 20))

#fig = plt.figure(1,1,figsize=(10, 10))
fig,axes = plt.subplots(3,1,figsize=(10, 18))
plt.subplots_adjust(left=0.01,right=0.99,bottom=0,top=0.99,hspace=0.01)

font = {'family' : 'SimSun','weight' : 'bold','size' : 10}
plt.rc('font', **font)
header=['日期','红盘','绿盘','总数','红盘率','绿盘率','强弱','涨幅1/2','跌幅1/2','跌停','涨停','炸板','首板','2连板','3连板','3板以上']

for i in [0,1,2]:
  me = pd.read_csv(csvs[i], encoding = 'gbk')
  c = me.tail(18)

  axes[i].text(0.4,0.993,titles[i], fontsize=15, color='r')
  axes[i].axis('off')
  
  the_table = axes[i].table(cellText=c.values,
                       # rowLabels=None,
                       # rowColours=colors,
                        colLabels=header,
                        cellLoc = 'center',colLoc='center',loc = 'center')
  the_table.auto_set_font_size(False)
  the_table.set_fontsize(13)
  
      
  for (row, col), cell in the_table.get_celld().items():
      if (row == 0):
          cell.set_text_props(fontproperties=FontProperties(weight='bold', size=12))
      else:
          cell.set_text_props(fontproperties=FontProperties(weight='bold', size=12))
      cell.set_height(1/20)
      if(row >=1 and col == 6):
         if(c.values[row-1][col] == '普涨'):
            cell.set_color((0.89, 0, 0))
         elif(c.values[row-1][col] == '普跌'):
            cell.set_color((0, 0.8, 0))
      elif(col == 0):
         cell.get_text().set_color((0.1, 0.2, 0.8))
      elif(col == 1 or col == 4):
         cell.get_text().set_color((0.6, 0.1, 0.1))
      elif(col == 2 or col == 5):
         cell.get_text().set_color((0.1, 0.6, 0.1))


#plt.show()   


plt.savefig(fundflow_png)   



print('--end')
#sys.exit(0)
